package com.hht.checkversion;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;

/**
 * Author: chenhu
 * Time: 2020/1/6 10:44
 * Description do somethings
 */
public class FileTools {
    public final static String STORAGE_PATH = "/storage/emulated/0";
    public final static String SYSTEM_PATH = "/mnt/sdcard";
    public static final String NULL_FILE_TAG = "dev/null";//空文件过滤掉

    //得到usb路径
    public static String getStoragePaths(Context cxt) {

        StorageManager storageManager = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE);
        try {
            Method method = StorageManager.class.getDeclaredMethod("getVolumePaths");
            method.setAccessible(true);
            Object result = method.invoke(storageManager);
            if (result != null && result instanceof String[]) {
                String[] pathes = (String[]) result;
                StatFs statFs;
                for (String path : pathes) {
                    if (path.equals(STORAGE_PATH)) {
                        path = SYSTEM_PATH;
                    }
                    if (!TextUtils.isEmpty(path) && new File(path).exists()) {
                        statFs = new StatFs(path);
                        if ((statFs.getBlockCount() * statFs.getBlockSize() != 0)) {
                            if (!path.contains(NULL_FILE_TAG) && !path.contains("sdcard")) {
                                return path;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return "";
    }

    //usb名字
    public static String getUsbDeviceLabel(Context context, String strMountPath) {

        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        try {

            Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList", new Class[0]);

            getVolumeList.setAccessible(true);

            Class<?> classStorageVolume = Class.forName("android.os.storage.StorageVolume");

            Method getPath = classStorageVolume.getDeclaredMethod("getPath", new Class[0]);

            Method getLabel = classStorageVolume.getDeclaredMethod("getUserLabel", new Class[0]);

            Object[] volumes = (Object[]) getVolumeList.invoke(storageManager, new Object[0]);

            if (volumes != null) {

                for (int i = 0; i < volumes.length; i++) {
                    String path = (String) getPath.invoke(volumes[i], new Object[0]);
                    String label = (String) getLabel.invoke(volumes[i], new Object[0]);
                    if (path.equals(strMountPath)) {
                        return label;
                    }
                }
            }
            if (!strMountPath.isEmpty()) {
                int subInt = strMountPath.lastIndexOf("/");
                strMountPath = strMountPath.substring(subInt + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strMountPath;
    }

    /**
     * 复制文件 <功能说明>
     *
     * @param @param oldPath
     * @param @param newPath
     */

    public static boolean copyFile(String oldPath, String newPath) {
        boolean isCopyFileSuccess = false;
        FileInputStream fis = null;
        RandomAccessFile raf = null;
        try {
            File oldFile = new File(oldPath);
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            if (oldFile.exists()) { //文件存在时
                fis = new FileInputStream(oldPath);
                raf = new RandomAccessFile(newFile.getPath(), "rwd");
                raf.setLength(0);//清除旧文件
                byte[] buf = new byte[3 * 1024 * 1024];
                int readline = 0;
                while ((readline = fis.read(buf)) != -1) {
                    raf.write(buf, 0, readline);
                }
                if (newFile.length() > 1) {
                    isCopyFileSuccess = true;
                } else {
                    newFile.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //之前IO错误后就直接跳到catch，没有执行file.close的操作，现在把他们单独搞个try catch
        try {
            if (raf != null) {
                raf.close();
            }
            if (fis != null) {
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isCopyFileSuccess;
    }

    //得到文件的Uri
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public static File getFileByUri(Uri uri, Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA},
                        buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();
            return new File(path);
        } else {
            //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

    public static String createFolder(String path) {
        if (TextUtils.isEmpty(path)) {
            return path;
        }
        File newlineFile = new File(path, "newline");
        if (!newlineFile.exists()) {
            newlineFile.mkdir();
        }
        return newlineFile.getAbsolutePath();
    }
}
